import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store'

Vue.use(VueRouter)
// 懒加载 不加载 import 可以将页面分成一个一个的js文件
const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/base',
    name: 'base',
    component: () => import('../layout/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          auth: true,
        },
        component: () => import('../views/HomeView.vue'),
      },
      {
        path: 'about',
        name: 'about',
        meta: {
          auth: true,
        },
        component: () => import('../views/AboutView.vue'),
      },
    ],
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 路由的前置钩子函数 导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          fullpath: to.fullPath, // 让用户重新进入刚开始想进入的页面
        },
      })
    }
  } else {
    next()
  }
})

export default router
